package com.yanti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanti.domain.ResponseResult;
import com.yanti.domain.entity.UserWrongQuestions;
import com.yanti.domain.enums.AppHttpCodeEnum;
import com.yanti.domain.vo.QuestionsVo;
import com.yanti.domain.vo.UserWrongAnalysis;
import com.yanti.filter.LoginUserContextHolder;
import com.yanti.mapper.UserWrongQuestionsMapper;
import com.yanti.service.QuestionsService;
import com.yanti.service.UserWrongQuestionsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户错题本表(UserWrongQuestions)表服务实现类
 *
 * @author luo
 * @since 2025-04-07 16:30:30
 */
@Service("userWrongQuestionsService")
public class UserWrongQuestionsServiceImpl extends ServiceImpl<UserWrongQuestionsMapper, UserWrongQuestions> implements UserWrongQuestionsService {

    @Resource
    private QuestionsService questionsService;
    @Override
    public ResponseResult<?> getUserWrongQuestion() {
        // 获取用户id
        Long uid = LoginUserContextHolder.getUserId();
        if (Objects.nonNull(uid)) {
            List<UserWrongQuestions> wrongQuestion = getWrongQuestion(uid);
            return ResponseResult.okResult(wrongQuestion);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }

    private List<UserWrongQuestions> getWrongQuestion(Long uid) {
        // 根据用户id查询错题
        QueryWrapper<UserWrongQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        return list(queryWrapper);
    }

    @Override
    public ResponseResult<?> getUserUserWrongQuestionByQuestionId() {
        // 获取用户id
        Long uid = LoginUserContextHolder.getUserId();
        // 获取用户错题id
        if (Objects.nonNull(uid)) {
            List<UserWrongQuestions> wrongQuestion = getWrongQuestion(uid);
            // 获取用户答案
            Map<Long, String> userQuestionIdAnswerMap = wrongQuestion.stream()
                    .collect(Collectors.toMap(UserWrongQuestions::getQuestionId, UserWrongQuestions::getUserAnswer));
            List<Long> questionIds = wrongQuestion.stream()
                    .map(UserWrongQuestions::getQuestionId)
                    .collect(Collectors.toList());
            // 根据用户错题id查询用户错题
            List<QuestionsVo> questionsByQuestionIds = questionsService.getQuestionsByQuestionIds(questionIds);
            // 封装到用户错题分析
            List<UserWrongAnalysis> userWrongAnalysisList = questionsByQuestionIds.stream()
                    .map(questionsVo -> new UserWrongAnalysis(questionsVo, userQuestionIdAnswerMap.get(questionsVo.getId())))
                    .toList();
            return ResponseResult.okResult(userWrongAnalysisList);
        }
        return null;
    }
}

